package com.swordxu.yim.server.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.swordxu.yim.server.packet.LoginPacket;
import com.swordxu.yim.server.packet.base.DefaultHeader;
import com.swordxu.yim.server.packet.base.Header;
import com.swordxu.yim.server.utils.ProtocolConstant;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

import javax.net.ssl.SSLException;

/**
 * Created by user063 on 2014/12/3.
 */
public class HelloWordClient {
    static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
    private static ChannelHandlerContext chCtx;

    public static void main(String args[]) throws InterruptedException, SSLException {
        // Client服务启动器 3.x的ClientBootstrap 改为Bootstrap，且构造函数变化很大，这里用无参构造。
        Bootstrap bootstrap = new Bootstrap();
        final SslContext sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
        // 指定channel类型
        bootstrap.channel(NioSocketChannel.class);
        // 指定Handler
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
//                p.addLast(sslCtx.newHandler(ch.alloc(), "127.0.0.1", 8000));
//                p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
//                p.addLast("frameEncoder", new LengthFieldPrepender(4));
//                p.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
//                p.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
//                p.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                p.addLast(new StringDecoder());
                p.addLast(new StringEncoder());
                //p.addLast(new LoggingHandler(LogLevel.INFO));
                p.addLast(new HelloClientHandler());
            }
        });
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        // 指定EventLoopGroup
        bootstrap.group(new NioEventLoopGroup());

        // 连接到本地的8000端口的服务端
        ChannelFuture ft = bootstrap.connect("127.0.0.1", 8000);
//        bootstrap.group().shutdownGracefully();
//        Scanner sc = new Scanner(System.in);
//        ft.sync().channel().writeAndFlush("测试消息ddddddddddddddddd").sync();
        LoginPacket loginPacket = new LoginPacket();
        Header header = new DefaultHeader(ProtocolConstant.SID_LOGIN, ProtocolConstant.CID_LOGIN_RES_MSGSERVER);
        LoginPacket.PacketRequest rs = new LoginPacket.PacketRequest();
        rs.entity.name = "sword2";
        rs.entity.pwd = "abc123";
        rs.setHeader(header);
        loginPacket.setmRequest(rs);
        JSONObject jo = new JSONObject();
        jo.put("header", header);
        JSONObject body = new JSONObject();
        body.put("name", rs.entity.name);
        body.put("pwd", rs.entity.pwd);
        jo.put("body", body);
        ft.sync().channel().writeAndFlush(jo.toJSONString()).sync();
//        while(true) {
//            String line = sc.nextLine();
//            if (line.equals("exit")) break;
////            ByteBuf buf = ft.channel().alloc().buffer(line.length());
////            buf.writeBytes(line.getBytes());
//            ft.channel().writeAndFlush(line);
//        }

    }

    private static class HelloClientHandler extends
            SimpleChannelInboundHandler<String> {

        public HelloClientHandler() {
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
//            super.channelActive(ctx);
            System.out.println("连接登录服务器");

        }

        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
            System.out.println(msg);
            JSONObject jo = JSON.parseObject(msg);
            JSONObject joBody = jo.getJSONObject("body");
            if (joBody.getInteger("result") == 102) {
                LoginPacket loginPacket = new LoginPacket();
                Header header = new DefaultHeader(ProtocolConstant.SID_LOGIN, ProtocolConstant.CID_LOGIN_RES_USERLOGIN);
                LoginPacket.PacketRequest rs = new LoginPacket.PacketRequest();
                rs.entity.name = "sword";
                rs.entity.pwd = "abc123";
                rs.setHeader(header);
                loginPacket.setmRequest(rs);
                JSONObject jo2 = new JSONObject();
                jo2.put("header", header);
                JSONObject body = new JSONObject();
                body.put("name", rs.entity.name);
                body.put("pwd", rs.entity.pwd);
                jo2.put("body", body);
                channelHandlerContext.writeAndFlush(jo2.toJSONString());
            }
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }

        @Override
        public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {

        }
    }
}

